package com.baijiaxing.weixin.family.common.consts;

/**
 * Created by June on 2016/12/18.
 */

import com.baijiaxing.weixin.family.common.http.HttpRequest;
import com.baijiaxing.weixin.family.common.http.HttpRequestModel;
import net.sf.json.JSON;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
public class FamilyTokenUtil {

    Logger logger = LoggerFactory.getLogger(this.getClass());

    public String getToken() throws IOException {

        String url =  "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid="+FamilyConsts.CORPID+"&corpsecret="+FamilyConsts.SECRET;
        HttpRequestModel model = HttpRequest.httpRequestGet(url);
        if(model == null){
            return null;
        }
        if(StringUtils.isBlank(model.getContent())){
            return null;
        }
        logger.info("token-json:{}",model.getContent());
        JSONObject obj = JSONObject.fromObject(model.getContent());
        if(obj == null||!obj.containsKey("access_token")||obj.get("access_token") == null||
                StringUtils.isBlank(obj.get("access_token").toString())){
            return null;
        }
        return obj.get("access_token").toString();
    }

}
